package com.xiaowenxiong.controller;

import com.xiaowenxiong.entity.Course;
import com.xiaowenxiong.entity.Pager;
import com.xiaowenxiong.entity.Sc;
import com.xiaowenxiong.entity.Student;
import com.xiaowenxiong.service.CourseService;
import com.xiaowenxiong.service.ScService;
import com.xiaowenxiong.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * Created by 15c on 2017/5/5.
 */
@Controller
@RequestMapping("/students")
public class StudentController {
    @Autowired
    StudentService studentService;
    @Autowired
    ScService scService;
    @Autowired
    CourseService courseService;


    @RequestMapping(value = "/student", method = RequestMethod.GET)
//    @GetMapping("/student")
    public String findOneStudent(Model model) {
        Student student = studentService.selectAstudentInfo("15001");
        model.addAttribute("Student", student);

        return "student/student";
    }

    /**
     * 删除一个学生
     *
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(HttpServletRequest httpServletRequest, HttpSession session) {
        String sno = httpServletRequest.getParameter("sno");
//        因为外键约束，先删成绩表中该生的成绩记录
        scService.deleteGrade(sno);
        int result = studentService.deleteOneStudent(sno);
        if (result == 1) {
            session.setAttribute("delete-type", "ok");
        } else {
            session.setAttribute("delete-type", "error");
        }
        return "redirect:/students/list";
    }

    /**
     * 得到用户更新页面
     *
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String getUpdateJsp(Model model, HttpServletRequest httpServletRequest) {
        String sno = httpServletRequest.getParameter("sno");
        Student student = studentService.selectAstudentInfo(sno);
        model.addAttribute("student", student);
        return "student/update";
    }


    /**
     * 更新学生信息
     *
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(HttpSession session, Student student) {
        int result = studentService.updateStudent(student);
        if (result == 1) {
            session.setAttribute("type", "ok");
        } else {
            session.setAttribute("type", "error");
        }
        return "redirect:/students/list";
    }


    /**
     * 用于查询所有学生信息
     *
     * @param model              用于将查询出的数据传到页面（pager对象里面封装了数据以及其他信息）
     * @param httpServletRequest 用于获取请求的pager.offset参数
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String findAllStudent(Model model, HttpServletRequest httpServletRequest) {
        int pageOffset = 0;
        try {
            pageOffset = Integer.parseInt(httpServletRequest.getParameter("pager.offset"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        model.addAttribute("pager", studentService.find(pageOffset));
        return "student/list";
    }

    /**
     * 得到添加用户页面
     *
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addJsp() {
        return "student/add";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(HttpSession session, @Validated Student student, BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
            return "student/add";
        } else {
            Student student1 = studentService.selectAstudentInfo(student.getSno());
            if (student1 != null) {
                model.addAttribute("type", student.getSno() + "该学号已经存在！");
                return "student/add";
            } else {

                int result = studentService.addStudent(student);
                if (result == 1) {
                    session.setAttribute("add-type", "ok");
                } else {
                    session.setAttribute("add-type", "error");
                }
                return "redirect:/students/list";
            }
        }
    }

    /**
     * 用于关键字筛选
     *
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/retrieval", method = RequestMethod.GET)
    public String retrievalStudents(HttpServletRequest httpServletRequest, Model model, String keyword, HttpSession session) {
        int pageOffset = 0;
        try {
            pageOffset = Integer.parseInt(httpServletRequest.getParameter("pager.offset"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        if (keyword.equals("")) {
            return "redirect:/students/list";
        } else {
            model.addAttribute("keyword", keyword);
            Pager<Student> pager = studentService.findStudnetByRetrieval(pageOffset, keyword);
            if (pager.getDatas().isEmpty()){
                return "student/noRetrieval";
            }
                model.addAttribute("pager", pager);
            return "student/student_retrieval_list";
        }
    }


    /**
     * 用于全部成绩查看
     *
     * @return
     */
    @RequestMapping(value = "/view_results", method = RequestMethod.GET)
    public String view_results(Model model, HttpServletRequest httpServletRequest, HttpSession httpSession) {
        String sno = httpServletRequest.getParameter("sno");
        Double result = null;
        Double credit = (double) 0;
        result = scService.getAllCcredit(sno);
        if (result != null) {
            model.addAttribute("credit", result);
        } else {
            model.addAttribute("credit", credit);
        }
        List<Student> studentList = studentService.selectGrade(sno);
        if (studentList.isEmpty()) {
            return "student/noGrade";
        } else {
            model.addAttribute("studentList", studentList);
            return "student/view_results";
        }

    }


    /**
     * 得到添加学生成绩修改页面
     *
     * @return
     */
    @RequestMapping(value = "/update_grade", method = RequestMethod.GET)
    public String updateGradeJsp(Model model, HttpServletRequest httpServletRequest) {
        String sno = httpServletRequest.getParameter("sno");
        Integer cno = null;
        try {
            cno = Integer.parseInt(httpServletRequest.getParameter("cno"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        Student student = studentService.selectInfoStudentAndCourseAndSc(sno, cno);
        model.addAttribute("student", student);
        return "student/update_grade";
    }

    @RequestMapping(value = "/update_grade", method = RequestMethod.POST)
    public String updateGrade(HttpServletRequest httpServletRequest, HttpSession session) {
        String sno = null;
        Integer cno = null;
        Float grade = null;
        Sc sc = new Sc();
        try {
            cno = Integer.parseInt(httpServletRequest.getParameter("cno"));
            sno = httpServletRequest.getParameter("sno");
            grade = Float.parseFloat(httpServletRequest.getParameter("grade"));
            sc.setSno(sno);
            sc.setCno(cno);
            sc.setGrade(grade);
            int result = scService.updateGrade(sc);
            if (result == 1) {
                session.setAttribute("update_grade-type", "ok");
            } else {
                session.setAttribute("update_grade-type", "error");
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
        return "redirect:/students/view_results?sno=" + sno;
    }

    /**
     * 用于得到add_grade.jsp页面（录入成绩）
     *
     * @param model
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/add_grade", method = RequestMethod.GET)
    public String addGradeJsp(Model model, HttpServletRequest httpServletRequest) {
        String sno = httpServletRequest.getParameter("sno");
        String sname = httpServletRequest.getParameter("sname");
        model.addAttribute("sno", sno);
        model.addAttribute("sname", sname);
        //获得该学生还有那些课程没成绩
        List<Course> courseList = courseService.selectNotCourse(sno);
        if (courseList.isEmpty()) {
            return "student/noCourse";
        } else {
            model.addAttribute("courseList", courseList);
            return "student/add_grade";
        }
    }

    /**
     * 用于得到学生成绩录入
     *
     * @param httpServletRequest
     * @param session
     * @return
     */
    @RequestMapping(value = "/add_grade", method = RequestMethod.POST)
    public String addGrade(HttpServletRequest httpServletRequest, HttpSession session) {
        String sno = null;
        Integer cno = null;
        Float grade = null;
        Sc sc = new Sc();
        try {
            sno = httpServletRequest.getParameter("sno");
            cno = Integer.parseInt(httpServletRequest.getParameter("cno"));
            grade = Float.parseFloat(httpServletRequest.getParameter("grade"));
            sc.setSno(sno);
            sc.setCno(cno);
            sc.setGrade(grade);
            int result = scService.addGrade(sc);
            if (result == 1) {
                session.setAttribute("add_grade-type", "ok");
            } else {
                session.setAttribute("add_grade-type", "error");
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
        return "redirect:/students/view_results?sno=" + sno;
    }

    /**
     * 用于全部课程信息展示
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/course_list", method = RequestMethod.GET)
    public String showAllCourse(Model model) {
        List<Course> courseList = courseService.selectAllCoursesInfo();
        model.addAttribute("courseList", courseList);
        return "student/course_list";
    }

    /**
     * 用于得到课程更新页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/course_update", method = RequestMethod.GET)
    public String course_updateJsp(Model model, HttpServletRequest request) {
        Integer cno = null;
        try {
            cno = Integer.parseInt(request.getParameter("cno"));
        } catch (Exception e) {
            e.getStackTrace();
        }
        Course course = courseService.selectAcourseInfo(cno);
        model.addAttribute("course", course);
        return "student/course_update";
    }

    /**
     * 用于处理课程更新数据
     *
     * @return
     */
    @RequestMapping(value = "/course_update", method = RequestMethod.POST)
    public String course_update(Course course, HttpSession session) {
        int result = courseService.updateCourseInfo(course);
        if (result == 1) {
            session.setAttribute("course_update-type", "ok");
        } else {
            session.setAttribute("course_update-type", "error");
        }
        return "redirect:/students/course_list";
    }


    /**
     * 用于得到课程添加页面
     *
     * @return
     */
    @RequestMapping(value = "/course_add", method = RequestMethod.GET)
    public String course_addJsp() {
        return "student/course_add";
    }

    /**
     * 用于处理课程添加数据
     *
     * @param course
     * @param session
     * @return
     */
    @RequestMapping(value = "/course_add", method = RequestMethod.POST)
    public String course_add(@Validated Course course, BindingResult bindingResult, HttpSession session, Model model) {
        if (bindingResult.hasErrors()) {
            return "student/course_add";
        } else {
            Course course1 = courseService.selectAcourseInfo(course.getCno());
            if (course1 != null) {
                model.addAttribute("type", course.getCno() + "该课程号已存在");
                return "student/course_add";
            } else {


                int result = courseService.insertNewCourse(course);
                if (result == 1) {
                    session.setAttribute("course_add-type", "ok");
                } else {
                    session.setAttribute("course_add-type", "error");
                }
                return "redirect:/students/course_list";
            }
        }
    }

    /**
     *用于删除成绩
     * @param sno
     * @param cno
     * @return
     */
    @RequestMapping(value = "/grade_delete", method = RequestMethod.GET)
    public String grade_delete(String sno,Integer cno,HttpSession session){
        Sc sc=new Sc();
        sc.setSno(sno);
        sc.setCno(cno);
        int result=scService.deleteOneGrade(sc);
        if (result == 1) {
            session.setAttribute("grade_delete-type", "ok");
        } else {
            session.setAttribute("grade_delete-type", "error");
        }
        return "redirect:/students/view_results?sno=" + sno;
    }
}
